package com.chenssy.register.controller;

import com.chenssy.common.core.InstanceInfo;
import com.chenssy.common.dto.*;
import com.chenssy.common.enums.ResponseStatusEnum;
import com.chenssy.register.core.InstanceRegister;
import com.chenssy.common.core.RecentlyChangedServiceInstance;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping
public class RegisterServerController {

    /**
     * 服务注册
     * @param request
     * @return
     */
    @PostMapping("/register")
    public RegisterResponse register(@RequestBody RegisterRequest request) {
        InstanceInfo instanceInfo = InstanceInfo.builder()
                                    .serviceName(request.getServiceName())
                                    .serviceInstanceId(request.getServiceInstanceId())
                                    .ip(request.getIp())
                                    .port(request.getPort())
                                    .build();

        InstanceRegister.getInstance().register(instanceInfo);

        return new RegisterResponse(ResponseStatusEnum.SUCCESS);
    }


    /**
     * 续约
     * @param request
     * @return
     */
    @PostMapping("/renew")
    public HearbeatResponse renew(@RequestBody HearbeatRequest request) {
       Boolean result = InstanceRegister.getInstance().renew(request.getServiceName(),request.getServiceInstanceId());

       HearbeatResponse response ;
       if (result) {
           response = new HearbeatResponse(ResponseStatusEnum.SUCCESS);
       } else {
           response = new HearbeatResponse(ResponseStatusEnum.ERROR);
       }

       return response;
    }

    /**
     * 拉取注册表
     * @return
     */
    @GetMapping("/pullRegistry")
    public PullRegistryResponse pullRegistry() {
        PullRegistryResponse response = new PullRegistryResponse();
        response.setRegistry(InstanceRegister.getInstance().getAllRegistry());

        return response;
    }

    /**
     * 增量拉取注册表
     * @return
     */
    @GetMapping("/fetchDeltaServiceRegisitry")
    public DeltaRegistry fetchDeltaServiceRegisitry() {
        return InstanceRegister.getInstance().getRecentlyChangedRegistry();
    }


    @DeleteMapping("/cancel")
    public CancelResponse cancel(@RequestBody CancelRequest request) {
        boolean result = InstanceRegister.getInstance().cancel(request.getServiceName(),request.getServiceInstanceId());

        CancelResponse response ;
        if (result) {
            response = new CancelResponse(ResponseStatusEnum.SUCCESS);
        } else {
            response = new CancelResponse(ResponseStatusEnum.ERROR);
        }

        return response;
    }
}
